package com.service.role;

import com.common.PojoUtil;
import com.common.ResultUtil;
import com.entity.Menu;
import com.entity.OperationLog;
import com.entity.Role;
import com.entity.Role2Menu;
import com.entity.Role2Source;
import com.entity.Source;
import com.facade.log.IOperationLogFacadeCUD;
import com.facade.menu.IMenuFacadeR;
import com.facade.role.IRole2MenuFacadeCUD;
import com.facade.role.IRole2SourceFacadeCUD;
import com.facade.role.IRoleFacadeCUD;
import com.facade.role.IRoleFacadeR;
import com.facade.source.ISourceFacadeR;
import com.facade.user.IManager2RoleFacadeCUD;
import com.mapper.CustomMapper;
import com.mapper.RoleMapper;
import com.service.CustomServiceCUD;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class RoleServiceCUD extends CustomServiceCUD<Role> implements IRoleFacadeCUD {

    @Resource
    private RoleMapper mapper;
    @Resource
    private IRoleFacadeR roleFacadeR;
    @Resource
    private IRole2SourceFacadeCUD role2SourceFacadeCUD;
    @Resource
    private IManager2RoleFacadeCUD manager2RoleFacadeCUD;
    @Resource
    private IRole2MenuFacadeCUD role2MenuFacadeCUD;
    @Resource
    private ISourceFacadeR sourceFacadeR;
    @Resource
    private IMenuFacadeR menuFacadeR;
    @Resource
    private IOperationLogFacadeCUD operationLogFacadeCUD;

    @Override
    protected CustomMapper<Role> initMapper() {
        return mapper;
    }


    @Override
    public ResultUtil addRole(Role role, Serializable... managerId) {
        Role _$0 = roleFacadeR.findUniqueByPropertyEqualTo("name", role.getName());
        ResultUtil resultUtil = ResultUtil.newInstance();
        if (null != _$0) {
            resultUtil.setStatus(ResultUtil.PARAM_VALID_FAILED);
            return resultUtil.setMessage("角色名称已存在");
        }
        if (null == role.getSeq()) {
            role.setSeq(0);
        }
        if (null == role.getStatus()) {
            role.setStatus(0);
        }
        role.setTop(0);
        addSelective(role);
        if (null != managerId && managerId.length > 0) {
            String message = "添加角色：[" + PojoUtil.notNull(role, "", "id") + "]";
            operationLogFacadeCUD.addOperationLog(managerId[0], OperationLog.ADD, message);
        }
        resultUtil.setMessage("添加成功");
        return resultUtil;
    }

    @Override
    public ResultUtil modifyRole(Role role, Serializable... managerId) {
        Long id = role.getId();
        ResultUtil resultUtil = ResultUtil.newInstance();
        if (null != id) {
            Role _$0 = roleFacadeR.findByPrimaryKey(id);
            if (null == _$0) {
                resultUtil.setStatus(ResultUtil.FAILED);
                return resultUtil.setMessage("记录不存在或已被删除");
            }
            Role _$1 = roleFacadeR.findUniqueByPropertyEqualTo("name", role.getName());
            /*角色名称重复*/
            if (null != _$1 && !_$1.getId().equals(id)) {
                resultUtil.setStatus(ResultUtil.PARAM_VALID_FAILED);
                return resultUtil.setMessage("角色名称已存在");
            }
            role.setUpdated(new Date());
            update(role);
            if (null != managerId && managerId.length > 0) {
                String message = "修改角色：[" + PojoUtil.compareDifferent(_$0, role, "", "id", "name") + "]";
                operationLogFacadeCUD.addOperationLog(managerId[0], OperationLog.MODIFY, message);
            }
            resultUtil.setMessage("修改成功");
        }
        return resultUtil;
    }

    @Override
    public ResultUtil modifyRoleSource(Long id, Long[] sourceIdArray, Serializable... managerId) {
        ResultUtil resultUtil = ResultUtil.newInstance();
        Role role = roleFacadeR.findByPrimaryKey(id);
        if (null == role) {
            resultUtil.setStatus(ResultUtil.FAILED);
            return resultUtil.setMessage("记录不存在或已被删除");
        }
        if (Integer.valueOf("1").equals(role.getTop())) {
            resultUtil.setStatus(ResultUtil.FAILED);
            return resultUtil.setMessage("超级角色权限不能修改");
        }
        List<Source> oldSources = null;
        if (null != managerId && managerId.length > 0) {
            oldSources = sourceFacadeR.findByRoleLink(id,
                    "parent_module_order ASC, parent_module ASC, child_module_order ASC, child_module ASC, seq ASC");
        }
        role2SourceFacadeCUD.deleteByPropertyEqualTo("roleId", id);
        if (null != sourceIdArray && sourceIdArray.length > 0) {
            List<Role2Source> role2SourceList = new ArrayList<>();
            for (Long sourceId : sourceIdArray) {
                role2SourceList.add(new Role2Source(id, sourceId));
            }
            role2SourceFacadeCUD.addBatch(role2SourceList);
        }
        if (null != managerId && managerId.length > 0) {
            String message = "修改角色（" + role.getName() + "）权限：[";
            List<Long> ids = new ArrayList<>();
            for (int i = 0; i < oldSources.size(); i++) {
                ids.add(oldSources.get(i).getId());
            }
            for (int i = 0; i < ids.size(); i++) {
                message += ids.get(i);
                if (i != ids.size() - 1) {
                    message += "、";
                }
            }
            message += " -> ";
            ids.clear();
            ids.addAll(Arrays.asList(sourceIdArray));
            Collections.sort(ids);
            for (int i = 0; i < ids.size(); i++) {
                message += ids.get(i);
                if (i != ids.size() - 1) {
                    message += "、";
                }
            }
            message += "]";
            operationLogFacadeCUD.addOperationLog(managerId[0], OperationLog.MODIFY, message);
        }
        resultUtil.setMessage("修改角色权限成功");
        return resultUtil;
    }

    @Override
    public ResultUtil modifyRoleMenu(Long id, Long[] menuIdArray, Serializable... managerId) {
        Role role = roleFacadeR.findByPrimaryKey(id);
        ResultUtil resultUtil = ResultUtil.newInstance();
        if (null == role) {
            resultUtil.setStatus(ResultUtil.FAILED);
            return resultUtil.setMessage("记录不存在或已被删除");
        }
        List<Menu> oldMenus = null;
        if (null != managerId && managerId.length > 0) {
            oldMenus = menuFacadeR.findByRoleLink(id);
        }
        role2MenuFacadeCUD.deleteByPropertyEqualTo("roleId", id);
        if (null != menuIdArray && menuIdArray.length > 0) {
            List<Role2Menu> role2MenuList = new ArrayList<>();
            for (Long menuId : menuIdArray) {
                role2MenuList.add(new Role2Menu(id, menuId));
            }
            role2MenuFacadeCUD.addBatch(role2MenuList);
        }
        if (null != managerId && managerId.length > 0) {
            String message = "修改角色（" + role.getName() + "）菜单：[";
            List<Long> ids = new ArrayList<>();
            for (int i = 0; i < oldMenus.size(); i++) {
                ids.add(oldMenus.get(i).getId());
            }
            Collections.sort(ids);
            for (int i = 0; i < ids.size(); i++) {
                message += ids.get(i);
                if (i != ids.size() - 1) {
                    message += "、";
                }
            }
            message += " -> ";
            ids.clear();
            ids.addAll(Arrays.asList(menuIdArray));
            Collections.sort(ids);
            for (int i = 0; i < ids.size(); i++) {
                message += ids.get(i);
                if (i != ids.size() - 1) {
                    message += "、";
                }
            }
            message += "]";
            operationLogFacadeCUD.addOperationLog(managerId[0], OperationLog.MODIFY, message);
        }
        resultUtil.setMessage("修改角色菜单成功");
        return resultUtil;
    }

    @Override
    public ResultUtil deleteRole(Serializable id, Serializable... managerId) {
        Role role = roleFacadeR.findByPrimaryKey(id);
        ResultUtil resultUtil = ResultUtil.newInstance();
        if (null == role) {
            resultUtil.setStatus(ResultUtil.FAILED);
            return resultUtil.setMessage("角色不存在或已被删除");
        }
        if (Integer.valueOf("1").equals(role.getTop())) {
            resultUtil.setStatus(ResultUtil.FAILED);
            resultUtil.setMessage("超级角色不能删除");
            return resultUtil;
        }
        /*删除中间表数据*/
        role2SourceFacadeCUD.deleteByPropertyEqualTo("roleId", id);
        role2MenuFacadeCUD.deleteByPropertyEqualTo("roleId", id);
        manager2RoleFacadeCUD.deleteByPropertyEqualTo("roleId", id);
        deleteByPrimaryKey(id);
        if (null != managerId && managerId.length > 0) {
            String message = "删除角色：[" + PojoUtil.notNull(role, "", "id", "name") + "]";
            operationLogFacadeCUD.addOperationLog(managerId[0], OperationLog.DELETE, message);
        }
        resultUtil.setMessage("删除成功");
        return resultUtil;
    }

}